//
//  EmotionView.swift
//  01-表情键盘 Emotion
//
//  Created by wulei on 15/12/15.
//  Copyright © 2015年 wulei. All rights reserved.
//

import UIKit
// 可重用CellID
private let EmotionViewCellID = "EmotionViewCellID"

class EmotionView: UIView {
    
    //MARK: - 选中表情回调
    private var selectedEmoticonCallBack: (emoticon: Emoticon) -> ()
    
    
// MARK: - UIBarButtomItem监听方法
    
    @objc private func clickItem(item: UIBarButtonItem) {
let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
    
    init(selectedEmoticon: (emoticon: Emoticon) -> ()) {
        
        // 记录闭包属性
        selectedEmoticonCallBack = selectedEmoticon
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = 216
        
        super.init(frame: rect)
        
        backgroundColor = UIColor.redColor()
        setupUI()
        
        
        // 默认滚动到第一页
        let indexPath = NSIndexPath(forItem: 0, inSection: 1)
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        }
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 懒加载控件
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmotionLayout())
    private lazy var toolBar = UIToolbar()
    
    // 表情包数组
    private lazy var packages = EmoticonManager.sharedManager.packages
    
    
    // MARK: - 表情布局 类中类(只允许被包含的类调用)
   private class EmotionLayout: UICollectionViewFlowLayout {
        
//        prepareLayout 
//        collectionView 第一次布局的时候被调用
        
        override func prepareLayout() {
            super.prepareLayout()
            
            let col: CGFloat = 7
            let row: CGFloat = 3
            
            let w = UIScreen.mainScreen().bounds.width / col
            
            itemSize = CGSize(width: w, height: w)
            
            let margin = (collectionView!.bounds.height - row * w) * 0.5
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
            
            scrollDirection = .Horizontal
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
            collectionView?.showsHorizontalScrollIndicator = false
            

            
        }
        
        
        
    }
    

}

extension EmotionView {
    func setupUI() {
        
        // 1.添加控件
        addSubview(collectionView)
        addSubview(toolBar)
        
        // 2.添加约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.bottom.equalTo(self.snp_bottom)
            make.height.equalTo(36)
        }
        
        collectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        // 准备控件
       prepareToolBar()
        prefareCollectionView()
        
    }
    
    // MARK: - 准备工具栏
    private func prepareToolBar() {
        // tintColor
        toolBar.tintColor = UIColor.darkGrayColor()
        var items = [UIBarButtonItem]()
        
        var index = 0
        // MARK: - BarButtonItem 的按钮点击事件
        
        for s in ["最近","默认","emoji","浪小花"] {
    items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
           items.append(UIBarButtonItem(title: s, style:.Plain, target: nil, action: "clickItem:"))
            items.last?.tag = index++
            
            // 添加弹簧效果
//            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action:nil))
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
        }
        
//        items.removeLast()
        toolBar.items = items
        
        
    }
    
    
    
    // 准备CollectionView
    private func prefareCollectionView() {
        collectionView.backgroundColor = UIColor.lightGrayColor()
        
        // MARK: - 注册重用ID
        collectionView.registerClass(EmoticonViewCell.self, forCellWithReuseIdentifier: EmotionViewCellID)
        // 设置数据源
        collectionView.dataSource = self
        // 设置代理
        collectionView.delegate = self
    }
}

// MARK: - 实现数据源方法
extension EmotionView: UICollectionViewDataSource, UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let vm = packages[indexPath.section].emoticons[indexPath.item]
        selectedEmoticonCallBack(emoticon: vm)
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return packages[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmotionViewCellID, forIndexPath: indexPath) as! EmoticonViewCell
        
        cell.backgroundColor = indexPath.row % 2 == 0 ? UIColor.redColor() : UIColor.yellowColor()
        cell.emoticon = packages[indexPath.section].emoticons[indexPath.item]
        return cell
    }
}

// MARK: - 自定义Cell (表情视图)
private class EmoticonViewCell: UICollectionViewCell {
    
    // 表情模型
    var emoticon: Emoticon? {
        didSet{
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: .Normal)

            emoticonButton.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            
            if emoticon!.isRemoved {
                
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(emoticonButton)
        emoticonButton.backgroundColor = UIColor.whiteColor()

        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        emoticonButton.userInteractionEnabled = false
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    // 懒加载控件
    lazy var emoticonButton: UIButton = UIButton()
    
    
}